package com.sjb.sixteen_journey_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sjb.sixteen_journey_backend.common.CommonHandle;
import com.sjb.sixteen_journey_backend.common.R;
import com.sjb.sixteen_journey_backend.entity.*;
import com.sjb.sixteen_journey_backend.mapper.*;
import com.sjb.sixteen_journey_backend.service.IFollowerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjb.sixteen_journey_backend.utils.PostDataComparatorUtil;
import com.sjb.sixteen_journey_backend.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 关注与粉丝表 服务实现类
 * </p>
 *
 * @author jcz
 * @since 2024-07-16
 */
@Service
public class FollowerServiceImpl extends ServiceImpl<FollowerMapper, Follower> implements IFollowerService {

    @Autowired
    private FollowerMapper followerMapper;

    @Autowired
    private MyTimeMapper myTimeMapper;
    @Autowired
    private ShowTicketMapper showTicketMapper;
    @Autowired
    private ShareThingMapper shareThingMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CommonHandle commonHandle;
    @Override
    public R followerUser(Integer id) {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            QueryWrapper<Follower> wrapper = Wrappers.query();
            wrapper.eq("user_id",userId);
            User user = userMapper.selectById(userId);
            wrapper.clear();
            wrapper.eq("fans_id",id);
            User fans = userMapper.selectById(id);
            if(fans==null||user==null){
                return R.error("没找到该用户");
            }
            wrapper.clear();
            wrapper.eq("user_id",userId);
            wrapper.eq("fans_id",id);
            List<Follower> follower  = followerMapper.selectList(wrapper);//找到该用户关注id为传入参数的用户，
            if(follower.size() <= 0){//关注表不存在此条记录，表明该用户从来没有关注此用户
                Follower follower1 = new Follower(null, user.getUserId(), user.getUsername(), user.getAvatar(), fans.getUserId(), fans.getUsername(), fans.getAvatar(), true);
                this.save(follower1);
                return R.success(follower1,"关注成功");
            }else {
                for(Follower f:follower){//修改关注状态status
                    if(f.getStatus()){//关注状态为true，表明该用户已经关注过此用户
    //                    f.setStatus(false);
    //                    this.updateById(f);
                        this.removeById(f.getFollowerId());
                        return R.success("取消关注成功",null);
                    }else {//关注状态为false，表明该用户没有关注过此用户
    //                    f.setStatus(true);
    //                    this.updateById(f);
    //                    return R.success(f,"关注成功");
                        Follower follower1 = new Follower(null, user.getUserId(), user.getUsername(), user.getAvatar(), fans.getUserId(), fans.getUsername(), fans.getAvatar(), true);
                        this.save(follower1);
                        return R.success(follower1,"关注成功");
                    }
                }
                return R.success(null,"操作成功");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R getFollower() {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            QueryWrapper<Follower> wrapper = Wrappers.query();
            wrapper.eq("user_id",userId);
            List<Follower> follower  = followerMapper.selectList(wrapper);
            return R.success(follower,"查询关注列表成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public R getFans() {
        try {
            Map<String, Object> map = ThreadLocalUtil.get();
            Integer userId = (Integer) map.get("id");
            QueryWrapper<Follower> wrapper = Wrappers.query();
            wrapper.eq("fans_id",userId);
            List<Follower> follower  = followerMapper.selectList(wrapper);
            return R.success(follower,"查询粉丝列表成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public <T> R getDCircleByFollower() throws IOException {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        QueryWrapper<Follower> wrapper = Wrappers.query();
        wrapper.eq("user_id",userId);
        List<Follower> follower  = followerMapper.selectList(wrapper);
        List<Object> data = new ArrayList<>();
        //找到登录用户的关注列表
        for(Follower f:follower){
            //将所有被关注的用户的发表动态的信息找到
            List<MyTime> allMyTimeByUserId = myTimeMapper.getAllMyTimeByUserId(f.getFansId());
            List<AirTicket> airTickets = showTicketMapper.selectAirTicketByUserId(f.getFansId());
            List<HotelTicket> hotelTickets = showTicketMapper.selectHotelTicketByUserId(f.getFansId());
            List<InsuranceTicket> insuranceTickets = showTicketMapper.selectInsuranceTicketByUserId(f.getFansId());
            List<OthersTicket> othersTickets = showTicketMapper.selectOthersTicketByUserId(f.getFansId());
            List<ShareThing> allShareThingByUserId = shareThingMapper.getAllShareThingByUserId(f.getFansId());

            //将字符串图片地址转换为数组
            for (MyTime myTime : allMyTimeByUserId) {
                if(myTime!=null){
                    List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                    myTime.setImages(strings);
                    data.add(myTime);
                }
            }
            for (AirTicket myTime : airTickets) {
                if(myTime!=null){
                    List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                    myTime.setImages(strings);
                    data.add(myTime);
                }

            }
            for (HotelTicket myTime : hotelTickets) {
                if(myTime!=null){
                    List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                    myTime.setImages(strings);
                    data.add(myTime);
                }
            }
            for (InsuranceTicket myTime : insuranceTickets) {
                if(myTime!=null){
                    List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                    myTime.setImages(strings);
                    data.add(myTime);
                }
                List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                myTime.setImages(strings);
            }
            for (OthersTicket myTime : othersTickets) {
                if(myTime!=null){
                    List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                    myTime.setImages(strings);
                    data.add(myTime);
                }
            }
            for (ShareThing myTime : allShareThingByUserId) {
                if(myTime!=null){
                    List<String> strings = commonHandle.imageByStringToList(myTime.getPath());
                    myTime.setImages(strings);
                    data.add(myTime);
                }
            }
            // 合并所有列表
//            for (List<?> list : Arrays.asList(allMyTimeByUserId, airTickets, hotelTickets, insuranceTickets, othersTickets, allShareThingByUserId)) {
//                for(Object l:list){
//                    if(l!=null){
//                        data.add(l);
//                    }
//                }
//            }
        }
        // 在合并所有列表后，使用自定义比较器对data列表进行排序
        Collections.sort(data, new PostDataComparatorUtil());
        return R.success(data,"操作成功");
    }
}
